package com.jiankangjin.transsystem.controller;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.jiankangjin.trading.dao.IOrderDataDao;
import com.jiankangjin.trading.dao.IPaymentDataDao;
import com.jiankangjin.trading.entity.OrderDataEntity;
import com.jiankangjin.trading.entity.PaymentDataEntity;
import com.jiankangjin.transsystem.common.Constant;
import com.jiankangjin.transsystem.util.StringUtil;
import com.jiankangjin.transsystem.util.TimeUtil;
import com.jiankangjin.transsystem.vo.NotifyVo;

/**
 * 接收所有订单变化通知,给渠道调用.
 */
@Controller
public class ChannelNotifyController {
	private static final Log logger=LogFactory.getLog(ChannelNotifyController.class);
	
	@Autowired
	IOrderDataDao orderDataDao;
	
	@Autowired
	IPaymentDataDao paymentDataDao;

	@RequestMapping(value="/channel_notify", method=RequestMethod.POST)
	@ResponseBody
	public NotifyVo channelNotify(
			@RequestParam(required = false) String notify_type,
			@RequestParam(required = false) String out_trade_no,
			@RequestParam(required = false) String order_id,
			@RequestParam(required = false) String pay_cry,
			@RequestParam(required = false) String pay_amt,
			@RequestParam(required = false) String pay_chnl_seq,
			@RequestParam(required = false) String pay_fin_time,
			@RequestParam(required = false) String pay_chnl_pos,
			@RequestParam(required = false) String pay_chnl_mer,
			@RequestParam(required = false) String pay_chnl_fee,
			@RequestParam(required = false) String pay_user,
			@RequestParam(required = false) String sub_deal_status,
			@RequestParam(required = false) String sub_deal_msg,
			@RequestParam(required = false) String sign
			) {
		StringBuilder sb = new StringBuilder();
		sb.append("notify_type=" + notify_type);
		sb.append(" out_trade_no=" + out_trade_no);
		sb.append(" order_id=" + order_id);
		sb.append(" pay_cry=" + pay_cry);
		sb.append(" pay_amt=" + pay_amt);
		sb.append(" pay_chnl_seq=" + pay_chnl_seq);
		sb.append(" pay_fin_time=" + pay_fin_time);
		sb.append(" pay_chnl_pos=" + pay_chnl_pos);
		sb.append(" pay_chnl_mer=" + pay_chnl_mer);
		sb.append(" pay_chnl_fee=" + pay_chnl_fee);
		sb.append(" pay_user=" + pay_user);
		sb.append(" sub_deal_status=" + sub_deal_status);
		sb.append(" sub_deal_msg=" + sub_deal_msg);
		sb.append(" sign=" + sign);
		logger.info("交易系统通知接口:"+sb);
		
		NotifyVo notifyVo = new NotifyVo();
		
		//验证
		if (StringUtil.isEmpty(notify_type)) {
			notifyVo.setResp_status("0001");
			notifyVo.setResp_msg("notify_type不能为空");
			return notifyVo;
		}
		if (StringUtil.isEmpty(out_trade_no)) {
			notifyVo.setResp_status("0002");
			notifyVo.setResp_msg("out_trade_no不能为空");
			return notifyVo;
		}
		if (StringUtil.isEmpty(pay_chnl_seq)) {
			notifyVo.setResp_status("0004");
			notifyVo.setResp_msg("pay_chnl_seq不能为空");
		}
		if (StringUtil.isEmpty(sub_deal_status)) {
			notifyVo.setResp_status("0005");
			notifyVo.setResp_msg("sub_deal_status不能为空");
		}
		if (StringUtil.isEmpty(sign)) {
			notifyVo.setResp_status("0006");
			notifyVo.setResp_msg("sign不能为空");
		}
		
		PaymentDataEntity payData = new PaymentDataEntity();
		OrderDataEntity orderData = new OrderDataEntity();
		payData = paymentDataDao.selectByPrimaryKey(out_trade_no);
		if (payData == null) {
			notifyVo.setResp_status("1001");
			notifyVo.setResp_msg("没找到支付记录");
			return notifyVo;
		}
		orderData = orderDataDao.selectByPrimaryKey(payData.getOrdSysId());
		if (orderData == null) {
			notifyVo.setResp_status("1002");
			notifyVo.setResp_msg("没找到订单记录");
			return notifyVo;
		}
		try {
			payData = new PaymentDataEntity();
			payData.setId(out_trade_no);
			payData.setPayCry(pay_cry);
			payData.setPayChnlSeq(pay_chnl_seq);
			payData.setPayFinTime(pay_fin_time);
			payData.setPayChnlPos(pay_chnl_pos);
			payData.setPayChnlMer(pay_chnl_mer);
			payData.setPayChnlFee(pay_chnl_fee);
			payData.setPayUser(pay_user);
			payData.setPayStat(sub_deal_status);
			if (paymentDataDao.update(payData)>0) {
				logger.info("支付已更新");
			}
			
			OrderDataEntity newOrderData = new OrderDataEntity();
			newOrderData.setId(orderData.getId());
			if (Constant.PAY_STAT_CODE_SUCCESS.equals(sub_deal_status)) {
				//本次支付成功的处理
				// 1) 订单状态 和 订单支付状态
				long allFee = Integer.parseInt(orderData.getOrdAmt());//订单总金额
				long agoFee = 0;//历史已支付总金额
				PaymentDataEntity example = new PaymentDataEntity();
				example.setOrdSysId(orderData.getId());
				example.setPayStat(Constant.PAY_STAT_CODE_SUCCESS);
				List<PaymentDataEntity> listPaymentData = paymentDataDao.listByEntity(example);
				for (int i = 0; i < listPaymentData.size(); i++) {
					agoFee += Integer.parseInt(listPaymentData.get(i).getPayAmt());//历史支付成功记录金额累加 
				}
				logger.info("订单金额=" + allFee +" 历史共支付=" + agoFee);
				if (agoFee != 0) {
					if(agoFee < allFee) {//部分支付
						newOrderData.setPayStat(Constant.ORD_PAY_STAT_CODE_PARTSUCCESS);
						newOrderData.setOrdStat(Constant.ORD_STAT_CODE_INIT);
					} else {//全部支付
						newOrderData.setOrdStat(Constant.ORD_STAT_CODE_SUCCESS);
						newOrderData.setPayStat(Constant.ORD_PAY_STAT_CODE_SUCCESS);
						newOrderData.setOrdFinTime(TimeUtil.getTime());//支付完成时间
					}
				}
				// 2) 已支付金额
				newOrderData.setPayAmt(""+agoFee);
			} else {
				//本次支付失败的处理
			}
			// 3) 订单状态不变
			// 4) 支付记录编号
			// 5) 订单支付时间
			newOrderData.setOrdPayTime(TimeUtil.getTime());//支付时间
			if (orderDataDao.update(newOrderData) >0) {
				logger.info("订单记录已更新");
			}
			
			notifyVo.setResp_status("0000");
			notifyVo.setResp_msg("通知成功");
			notifyVo.setFinish_time(TimeUtil.getTime());
			notifyVo.setSign("transSystem_channelNotify_sign");
			return notifyVo;
		} catch (Exception e) {
			notifyVo.setResp_status("9999");
			notifyVo.setResp_msg("通知失败，系统报错");
			logger.error(this, e);
		}
		return notifyVo;
	}
}
